<?php

/*
 * Query Commerce Cielo Module - payment method module for Magento,
 * integrating the billing forms with a Cielo's gateway Web Service.
 * Copyright (C) 2013  Fillipe Almeida Dutra
 * Belo Horizonte, Minas Gerais - Brazil
 * 
 * Contact: lawsann@gmail.com
 * Project link: http://code.google.com/p/magento-cielo/
 * Group discussion: http://groups.google.com/group/cielo-magento
 * 
 * Team: 
 * Fillipe Almeida Dutra - lawsann@gmail.com
 * Hermes Luciano Monteiro Junior - hermeslmj@gmail.com
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

?>
<fieldset class="form-list">
	<ul id="payment_form_Query_Cielo_Cc" style="display:none;">
	<br />
<?php
	
	$tokens = $this->getCieloTokens();
	
	if($tokens && (count($tokens) > 0) && ($this->getConfigData('tokenize') == 1))
	{
?>
		<p>Você deseja pagar com qual cartão?</p>
		<ul>
<?php
		foreach ($tokens as $token)
		{
			$img = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN) . "frontend/default/default/images/cielo/".$token['image']."";
			$lastDigits = Mage::Helper('core')->decrypt($token['last_digits']);
?>
			<li style="margin-bottom: 20px;">
				<table>
					<tr>
						<td style="width: 25px;">
							<input name="payment[token]" 
								   type="radio" 
								   value="<?php echo $token['cc_type'] . '/' . $token['id']; ?>" 
								   id="card-<?php echo $token['id']; ?>-tk" 
								   onclick="queryCieloUpdateInstallments('<?php echo $token["cc_type"]; ?>'); showCardData(false); unlockRequiredFields();"
								   class="validate-one-required-by-name"
								   style="margin-top: 3px;" />
						</td>
						<td>
							<label for="card-<?php echo $token['id']; ?>-tk"><img src="<?php echo $img; ?>" style="width: 40px;"> **** **** **** <?php echo $lastDigits; ?></label>
						</td>
					</tr>
				</table>
			</li>	
<?php
		}
?>
			<li>
				<table style="margin: 25px 0 10px 0;">
					<tr>
						<td style="width: 25px;">
							<input name="payment[token]" type="radio" value="" id="card-other" onclick="showCardData(true); lockRequiredFields();" />
						</td>
						<td>
							<label for="card-other">Outro Cartão: </label>
						</td>
					</tr>
				</table>
			</li>
		</ul>

<?php
	}
?>
	<div id='card-data'>
<?php

	$cardsData = $this->getAllowedCards();
	
	$size = count($cardsData);
	
	for($i = 0; $i < $size; $i++)
	{
		$value = $cardsData[$i]['value'];
		$label = $cardsData[$i]['label'];
		$img = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN) . "frontend/default/default/images/cielo/" . $cardsData[$i]['image'];
		
		// abre agrupamento de bandeiras
		if($i % 3 == 0)
		{
?>


		<li class="first">
		<ul class="card-logo">
<?php
		}
		
		// bandeira em questao
?>
			<li style="width: 70px; float: left;">
				<label for="card-<?php echo $value; ?>"><img src="<?php echo $img; ?>" style="width: 40px;" title="<?php echo $label; ?>" /><br>
					<input name="payment[cc_type]" type="radio" value="<?php echo $value; ?>" id="card-<?php echo $value; ?>" 
						   onclick="queryCieloUpdateInstallments('<?php echo $value; ?>')" class="validate-one-required-by-name" />
				</label>
			</li>

<?php
		// fecha agrupamento de bandeiras
		if(($i == $size - 1))
		{
?>
		</ul>
		</li>
<?php
		}
	}
	
	// dados do cartao
	// somente mostrado em buy page loja
	
	if($this->getConfigData('buypage') == "loja")
	{
?>
		<li>
			<label for="cielo-cc-card-number" class="required"><em>*</em><?php echo $this->__('Card Number') ?></label><br />
			<div class="input-box">
				<input name="payment[cc_number]" type="text" value="" id="cielo-cc-card-number" 
					   title="<?php echo $this->__('Card Number') ?>" class="input-text required-entry validate-cc-number" 
					   maxlength="19" onkeydown="return denyNotNumberCc(this, event);" autocomplete="off" />
			</div>
		</li>
		<li>
			<label for="cielo-cc-security-code" class="required"><em>*</em><?php echo $this->__('Verification Code') ?></label><br />
			<div class="input-box">
				<input name="payment[cc_cid]" type="text" value="" id="cielo-cc-security-code" title="<?php echo $this->__('Verification Code') ?>" class="input-text  required-entry" style="width: 50px;" maxlength="4" onkeydown="return denyNotNumberCc(this, event);"
				autocomplete="off" />
			</div>
		</li>
		<li>
			<label for="cielo-cc-card_expiration-mh" class="required"><em>*</em><?php echo $this->__('Expiration Date') ?></label>
			<div class="input-box">
				<div class="v-fix">
					<select id="cielo-cc-card_expiration-mh" name="payment[cc_exp_month]" class="month required-entry" autocomplete="off">
						<option value="" selected="selected"><?php echo $this->__('Month') ?></option>
						<?php foreach($this->getMonths() as $month): ?>
						<option value="<?php echo $month['num'] ?>"><?php echo $month['label'] ?></option>
						<?php endforeach ?>
					</select>
				</div>
				<div class="v-fix">
					<select id="cielo-cc-card_expiration-yr" name="payment[cc_exp_year]" class="year required-entry" autocomplete="off">
						<option value="" selected="selected"><?php echo $this->__('Year') ?></option>
						<?php foreach($this->getYears() as $year): ?>
						<option value="<?php echo $year['num'] ?>"><?php echo $year['label'] ?></option>
						<?php endforeach ?>
					</select>
				</div>
			</div>
			<li>
				<label for="cielo-cc-card_owner" class="required"><em>*</em><?php echo $this->__('Name on Card') ?></label>
				<div class="input-box">
					<input type="text" title="<?php echo $this->__('Name on Card') ?>" class="input-text required-entry" id="cielo-cc-card_owner" name="payment[cc_owner]" value="" autocomplete="off">
					<input type="hidden" id="cielo-current-cc-type" value="" />
				</div>
			</li>
		</li>
	</div>
	
<?php 
		if($tokens && (count($tokens) > 0) && ($this->getConfigData('tokenize') == 1))
		{
?>
		<script type="text/javascript">
			$('card-data').hide();
		</script>
<?php
		}
	}
?>
		<li>
			<br />
			<label for="cielo-installments" class="required"><em>*</em><?php echo $this->__('Installments') ?> </label>
			<div class="input-box">
				<select id="cielo-installments" name="payment[parcels_number]">
					<?php foreach($this->getInstallments() as $parcel): ?>
					<option value="<?php echo $parcel['num'] ?>"><?php echo $parcel['label'] ?></option>
					<?php endforeach ?>
				</select>
			</div>
		</li>
		<br />
	</ul>
	
</fieldset>

<script type="text/javascript">// <![CDATA[

	function queryCieloUpdateInstallments(cardType)
	{
		var installmentsField = document.getElementById('cielo-installments');
		
		// monta array com maximo de parcelas x bandeira cartao
		var installmentsArray = new Array();
<?php
	
	$cardsMaxInstallments = $this->getMaxCardsInstallments();
	
	foreach($cardsMaxInstallments as $card => $maxInstallments)
	{
		echo "installmentsArray." . $card . " = " . $maxInstallments . ";\n";
	}
	
?>
		
		// ajusta valor do campo
		if(installmentsField.value > installmentsArray[cardType])
		{
			installmentsField.value = 1;
		}
		
		// ajusta opcoes mostradas
		for(var i = 0; i < installmentsField.options.length; i++)
		{
			if(installmentsArray[cardType] < (i + 1))
			{
				installmentsField.options[i].style.display = "none";
			}
			else
			{
				installmentsField.options[i].style.display = "block";
			}
		}
		
		// limpa o restante do formulario
		cleanCcForm(cardType);
	}
	
	function denyNotNumberCc(field, event)
	{
        var keyCode = ('which' in event) ? event.which : event.keyCode;
		
		// teclas backspace e delete
        if(keyCode == 8 || keyCode == 46)
			return true;
		
		// tecla tab
        if(keyCode == 9)
			return true;
		
		// teclas <- e ->
        if(keyCode == 37 || keyCode == 39)
			return true;
		
		// teclas home e end
        if(keyCode == 36 || keyCode == 35)
			return true;
		
		// teclas numericas
        if((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105))
			return true;
        
		return false;
	}

	function showCardData(show)
	{
		if(show)
		{
			$('card-data').show();
		}
		else
		{
			$('card-data').hide();
		}
	}

	function unlockRequiredFields(){
		$('cielo-cc-card-number').removeClassName('required-entry');
		$('cielo-cc-security-code').removeClassName('required-entry');
		$('cielo-cc-card_expiration-mh').removeClassName('required-entry');
		$('cielo-cc-card_expiration-yr').removeClassName('required-entry');
		$('cielo-cc-card_owner').removeClassName('required-entry');
	}

	function lockRequiredFiedls(){
		$('cielo-cc-card-number').addClassName('required-entry');
		$('cielo-cc-security-code').addClassName('required-entry');
		$('cielo-cc-card_expiration-mh').addClassName('required-entry');
		$('cielo-cc-card_expiration-yr').addClassName('required-entry');
		$('cielo-cc-card_owner').addClassName('required-entry');	
	}
	
	function cleanCcForm(cardType)
	{
<?php
		
		if($this->getConfigData('buypage') == "loja")
		{
?>
		var currentCcType = document.getElementById('cielo-current-cc-type').value;
		document.getElementById('cielo-current-cc-type').value = cardType;
		
		if(currentCcType != cardType)
		{
			document.getElementById('cielo-cc-card-number').value = "";
			document.getElementById('cielo-cc-security-code').value = "";
			document.getElementById('cielo-cc-card_expiration-mh').value = "";
			document.getElementById('cielo-cc-card_expiration-yr').value = "";
			document.getElementById('cielo-cc-card_owner').value = "";
		}
<?php
		}
?>
	}

// ]]></script>
